import React, { useState } from 'react'
import { EditorState, convertToRaw, ContentState } from 'draft-js'
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'
import { Editor } from 'react-draft-wysiwyg'
import '../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import './index.less'
export default class RichEdit extends React.Component {
  state = {
    editorState: EditorState.createEmpty(),
  }
  //针对props数据还么传送，就已经开始渲染数据
  componentWillReceiveProps(nextProps) {
    if (nextProps.oldVal) {
      const contentBlock = htmlToDraft(nextProps.oldVal)
      if (contentBlock) {
        const contentState = ContentState.createFromBlockArray(
          contentBlock.contentBlocks
        )

        const editorState = EditorState.createWithContent(contentState)
        this.setState({
          editorState,
        })
      }
    }
  }
  onEditorStateChange = (editor) => {
    this.setState({
      editorState: editor,
    })
  }
  getRichContent = () => {
    return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
  }
  render() {
    return (
      <Editor
        editorState={this.state.editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="rich-edit"
        onEditorStateChange={this.onEditorStateChange}
      />
    )
  }
}
